package com.itany.netclass.service.impl;

import com.itany.mvc.util.CommonsMultipartFile;
import com.itany.netclass.constant.CourseConstant;
import com.itany.netclass.constant.CourseTypeConstant;
import com.itany.netclass.dao.ChapterMapper;
import com.itany.netclass.dao.CourseMapper;
import com.itany.netclass.dao.CourseTypeMapper;
import com.itany.netclass.entity.*;
import com.itany.netclass.exception.*;
import com.itany.netclass.factory.ObjectFactory;
import com.itany.netclass.service.ChapterService;
import com.itany.netclass.service.CourseService;
import com.itany.netclass.util.ParameterUtil;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * Author:sjy@itany.com
 * Date:21-10-14 下午6:36
 * Version:1.0-SNAPSHOT
 * Description:
 */
public class CourseServiceImpl implements CourseService {
    @Override
    public List<CourseType> findAllType(User user) throws NoLoginException {
        if(user==null){
            throw new NoLoginException("未登录，请先登录");
        }
        CourseTypeMapper courseTypeMapper = (CourseTypeMapper) ObjectFactory.getObject("CourseTypeMapper");
        List<CourseType> list = courseTypeMapper.selectFatherListOrder();
        return list;
    }

    @Override
    public List<Course> findAllCourse() {
        CourseMapper courseMapper = (CourseMapper) ObjectFactory.getObject("CourseMapper");
        return courseMapper.selectAllCourse();
    }

    @Override
    public void jianchaCourseName(String courseId,String courseName, String courseType) throws NullSringException, CourseExistException {
        if(ParameterUtil.isNull(courseName)){
            throw new NullSringException("课程名称不可以为空");
        }
        if("-1".equals(courseType)){
            return;
        }
        CourseMapper courseMapper = (CourseMapper) ObjectFactory.getObject("CourseMapper");
        CourseExample example =new CourseExample();
        if(!ParameterUtil.isNull(courseId) && !"-1".equals(courseType)){
            example.or()
                    .andCourseNameEqualTo(courseName)
                    .andIdNotEqualTo(Integer.parseInt(courseId))
                    .andCourseTypeIdEqualTo(Integer.parseInt(courseType));
        }else{
            example.or()
                    .andCourseNameEqualTo(courseName)
                    .andCourseTypeIdEqualTo(Integer.parseInt(courseType));
        }
        List<Course> courses = courseMapper.selectByExample(example);
        if(!courses.isEmpty()){
            throw new CourseExistException("同课程类型下存在同名课程");
        }

    }

    @Override
    public void jianchaCourseInfo(String courseInfo) throws NullSringException {
        if(ParameterUtil.isNull(courseInfo)){
            throw new NullSringException("课程简介不能为空");
        }
    }

    @Override
    public void jianchaCourseAuthor(String courseAuthor) throws NullSringException {
        if(ParameterUtil.isNull(courseAuthor)){
            throw new NullSringException("课程作者不能为空");
        }
    }

    @Override
    public void jianchaCourseTuijian(String courseTuijian) throws NullSringException {
        if("-1".equals(courseTuijian)){
            throw new NullSringException("请选择推荐程度");
        }
    }

    @Override
    public void jianchaCourseType(String courseId,String courseType ,String courseName) throws NullSringException, CourseExistException {
        if("-1".equals(courseType)){
            throw new NullSringException("请选择课程类型");
        }
        if(ParameterUtil.isNull(courseName)){
            return;
        }
        CourseMapper courseMapper = (CourseMapper) ObjectFactory.getObject("CourseMapper");
        CourseExample example =new CourseExample();
        System.out.println(courseId+"111111");
        if(!ParameterUtil.isNull(courseId) && !"-1".equals(courseType)){
            example.or()
                    .andCourseNameEqualTo(courseName)
                    .andIdNotEqualTo(Integer.parseInt(courseId))
                    .andCourseTypeIdEqualTo(Integer.parseInt(courseType));
        }else{
            example.or()
                    .andCourseNameEqualTo(courseName)
                    .andCourseTypeIdEqualTo(Integer.parseInt(courseType));
        }
        List<Course> courses = courseMapper.selectByExample(example);
        if(!courses.isEmpty()){
            throw new CourseExistException("同课程类型下存在同名课程");
        }

    }

    @Override
    public void jianchaCourseFile(String courseId, HttpSession session, List<CommonsMultipartFile> list) throws NullSringException, TypeExistException {
        if(ParameterUtil.isNull(courseId)&&
                ( list.isEmpty() || ParameterUtil.isNull(list.get(0).getOriginalFilename()))
        ){
            throw new NullSringException("添加课程时封面不可为空");
        }
        CommonsMultipartFile file =list.get(0);
        String name = file.getOriginalFilename();
        System.out.println(name);
        if(!(name.endsWith(".png") || name.endsWith(".jpg"))){
            throw new TypeExistException("图片格式错误，只支持png和jpg");
        }
    }

    @Override
    public void addCourse(String courseId, String courseName, String courseInfo, String author, String tuijian, String type, List<CommonsMultipartFile> list, HttpSession session) throws Exception {
        if(ParameterUtil.isNull(courseId)
                &&
         ( list.isEmpty() || ParameterUtil.isNull(list.get(0).getOriginalFilename()))
        ){
            throw new NullSringException("添加课程时封面不可为空");
        }
        System.out.println(list.get(0));
        CourseMapper courseMapper = (CourseMapper) ObjectFactory.getObject("CourseMapper");
        String path = CourseConstant.COURSE_IMAGES_PATH+new SimpleDateFormat("yyyyMMdd").format(new Date());
        String context = session.getServletContext().getRealPath(path);
        System.out.println(context);
        new File(context).mkdirs();
        CommonsMultipartFile file = list.get(0);
        String fileName = file.getOriginalFilename();
        fileName =fileName.substring(0,fileName.lastIndexOf("."))
                +new Date().getTime()+
                fileName.substring(fileName.lastIndexOf("."));
        String imagePath = path+"/"+fileName;
        System.out.println("数据库的数据="+imagePath);
        Course course =new Course();
        course.setCourseName(courseName);
        course.setCourseInfo(courseInfo);
        course.setAuthor(author);
        course.setCoverImageUrl(imagePath);
        course.setCreateDate(new Date());
        course.setRecommendationGrade(Integer.parseInt(tuijian));
        course.setClickNumber(Integer.parseInt(CourseConstant.COURSE_0_CLICK_NUMBER));
        course.setCourseTypeId(Integer.parseInt(type));

        //初始状态和课程类型一样
        CourseTypeMapper courseTypeMapper = (CourseTypeMapper) ObjectFactory.getObject("CourseTypeMapper");
        CourseType courseType = courseTypeMapper.selectByPrimaryKey(Integer.parseInt(type));
        course.setStatus(courseType.getStatus());
        try {
            courseMapper.insertSelective(course);
            file.transferTo(new File(context,fileName));
        } catch (Exception e) {
            throw e;
        }

    }

    @Override
    public Course findCourseById(String id) {
        CourseMapper courseMapper= (CourseMapper) ObjectFactory.getObject("CourseMapper");
        Course course = courseMapper.selectByPrimaryKey(Integer.parseInt(id));
        return course;
    }

    @Override
    public void modifyCourseById(String courseId, String courseName, String courseInfo, String author, String tuijian, String type, HttpSession session, List<CommonsMultipartFile> list) throws Exception {

        CourseMapper courseMapper= (CourseMapper) ObjectFactory.getObject("CourseMapper");
        Course course = new Course();
        String context="";
        String fileName="";
        if(!( ( list.isEmpty() || ParameterUtil.isNull(list.get(0).getOriginalFilename())))){
            String path = CourseConstant.COURSE_IMAGES_PATH+new SimpleDateFormat("yyyyMMdd").format(new Date());
            context = session.getServletContext().getRealPath(path);
            System.out.println(context);
            new File(context).mkdirs();
            CommonsMultipartFile file = list.get(0);
            fileName = file.getOriginalFilename();
            fileName =fileName.substring(0,fileName.lastIndexOf("."))
                    +new Date().getTime()+
                    fileName.substring(fileName.lastIndexOf("."));
            String imagePath = path+"/"+fileName;
            System.out.println("数据库的数据="+imagePath);
            course.setCoverImageUrl(imagePath);
        }
        course.setId(Integer.parseInt(courseId));
        course.setCourseName(courseName);
        course.setCourseInfo(courseInfo);
        course.setAuthor(author);
        course.setRecommendationGrade(Integer.parseInt(tuijian));
        course.setCourseTypeId(Integer.parseInt(type));

        try {
            System.out.println("000000000");
            courseMapper.updateByPrimaryKeySelective(course);
            if(! ( list.isEmpty() || ParameterUtil.isNull(list.get(0).getOriginalFilename()))){
                list.get(0).transferTo(new File(context,fileName));
            }
        }catch (Exception e) {
            throw e;
        }

    }

    @Override
    public void yongCourseById(String courseId, String status) throws Exception {
        CourseMapper courseMapper = (CourseMapper) ObjectFactory.getObject("CourseMapper");
        CourseTypeMapper courseTypeMapper = (CourseTypeMapper) ObjectFactory.getObject("CourseTypeMapper");
        ChapterMapper chapterMapper= (ChapterMapper) ObjectFactory.getObject("ChapterMapper");
        Course course = courseMapper.selectByPrimaryKey(Integer.parseInt(courseId));
        Integer courseTypeId = course.getCourseTypeId();
        CourseType courseType = courseTypeMapper.selectByPrimaryKey(courseTypeId);
        if(courseType.getStatus()== Integer.parseInt(CourseTypeConstant.COURSETYPE_STATUS_JINYONG)
                                              &&
          status.equals(CourseConstant.COURSE_STATUS_QIYONG)) {
            throw new NoQuanXianException(courseType.getTypeName()+"类型的被禁用，请先启用类型再修改");
        }
        if(!status.equals(""+course.getStatus())){
            course.setStatus(Integer.parseInt(status));
            courseMapper.updateByPrimaryKeySelective(course);
            //这里需要插入，课程被禁后所用的章节也被禁用的方法
            ChapterService chapterService= (ChapterService) ObjectFactory.getObject("ChapterServiceTarget");
            ChapterExample example = new ChapterExample();
            example.or()
                    .andCourseIdEqualTo(Integer.parseInt(courseId));
            List<Chapter> chapters = chapterMapper.selectByExample(example);
            if(!chapters.isEmpty()){
                for(Chapter c:chapters) {
                    chapterService.yongChapterById(courseId,""+c.getId(),status);
                }
            }
            //这里需要插入，课程被禁后所用的章节也被禁用的方法
        }

    }

    @Override
    public List<Course> sreachCourseByForm(String author, String courseName, String status, String type, String kaishitime, String jieshutime) throws NullSringException {
        CourseMapper courseMapper= (CourseMapper) ObjectFactory.getObject("CourseMapper");
        List<Course> courses = courseMapper.selectCourseByForm(author, courseName, status, type, kaishitime, jieshutime);
        if(courses.isEmpty()){
            throw new NullSringException();
        }else {
            return courses;
        }

    }

}
